package core;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class Record {
		
	public static final String END = "\0";
	
	private RecordType type;
	protected List<Field> fields;
	
	public Record(RecordType type,String... values) {
		this.type = type;
		if (values !=null) {
			for (String value : values) {
				fields.add(new Field(value));
			}
		}
	}
	
	public Record(RecordType type, List<Field> fields) {
		this.type = type;
		if(fields!=null) {
			this.fields = fields;
		}else {
			this.fields = new ArrayList<Field>();
		}
	}
	
	public RecordType getType() { return this.type; }
	
	public byte[] getBytes() throws UnsupportedEncodingException{
		return this.toString().getBytes("US-ASCII");
	}
	
	public boolean setField(String tag,String value) {
		if (this.fields != null) {
			for (Field field : fields) {
				if (field.getTag().equalsIgnoreCase(tag)) {
					field.setValue(value);
					return true;
				}
			}
		}
		return false;
	}
	
	public String toString() {
		StringBuilder result = new StringBuilder();

		result.append(type.tag+"=");
		for(int i=0;i<fields.size();i++) {
			result.append(fields.get(i).toString()+ ((i == fields.size()-1) ? "":Field.END));
		}
		if(fields.size()<2) {
			result.append(END);
		}
		return result.toString();
	}
		
	public enum RecordType {
		MSG("ms"),
		LEN("ln"),
		CMD("cm"),
		USER("id");
		
		private String tag;
		
		private RecordType(String tag) {
			this.tag = tag;
		}
		
		public String getTag() {
			return this.tag;
		}
	}
}